<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of PlayerChoise
 *
 * @author lpokoradi
 */
class PlayerChoise {
  const TYPE_XPATH = "./@type";
  const CHOISE_XPATH = ".";

  private $type;
  private $primary;
  private $db;

  public function __construct($database) {
    $this->db = $database;

    $this->type = "";
    $this->primary = "";
  }

  public function loadFromNode(DOMElement $docNode) {
    $doc = $docNode->ownerDocument;

    $xPath = new DOMXPath($doc);

    $qResult = $xPath->query(PlayerChoise::TYPE_XPATH,$docNode);
    $this->type = $qResult->item(0)->nodeValue;

    $qResult = $xPath->query(PlayerChoise::CHOISE_XPATH,$docNode);
    $this->primary = $qResult->item(0)->nodeValue;
  }

  public function insertNewToDB($playerId) {
    $this->db->set('playerId',$playerId);
    $this->db->set('type',$this->type);
    $this->db->set('primaryChoise',$this->primary);

    $query = $this->db->insert('playerchoice');

    if (!$query) {
      log_message('error', 'Error during playerage inserttion!');
      return false;
    }
    return $this->type.':'.$this->db->insert_id();
  }

  public function amendOldInDB($id) {
    $this->db->where('id',$id);
    $query = $this->db->get('playerchoice');

    if (!$query) {
      log_message('error','Error during playerchoice amendment!');
    } else {
      $tRow = $query->row();
      $oldId = $tRow->id;
      $playerId = $tRow->playerId;

      if ($tRow->primaryChoise!=$this->primary) {
        $newId = $this->insertNewToDB($playerId);

        $this->db->set('playerId', $playerId);
        $this->db->set('table','playerchoice');
        $this->db->set('oldId',$oldId);
        $this->db->set('newId',$newId);
        $this->db->set('insertTime',date('Y-m-d H:i:s'));
        $query = $this->db->insert('playerhistory');

        if (!$query) {
          log_message('error','Playerchoice amend was unsuccesful!');
        } else {
          return $this->type.':'.$newId;
        }
      }
    }
    return $this->type.':'.$oldId;
  }

  public function loadFromDB($choiceId) {
    $this->db->where('id',$choiceId);
    $query = $this->db->get('playerchoice');

    if (!$query || $query->num_rows()==0) {
      log_message('error', 'PlayerChoice ('.$choiceId.') not found in the database!');
    } else {
      $result = $query->row();

      $this->type = $result->type;
      $this->primary = $result->primaryChoise;
    }
  }

  public function getType() {
    return $this->type;
  }
}
?>
